const {
    RedisPrefix,
    Constant
} = require('./consts')


/**
 * 检查用户任务是否存在
 * @param uid
 * @param code
 * @returns {Promise<unknown>}
 */
exports.cacheSonList = function (uid, pageNum) {
    return new Promise((resolve, reject) => {
        let redis = this.app.get("redis");
        let cacheKey = RedisPrefix.SON_LIST_PREFIX + uid;
        let pageKey = RedisPrefix.PAGE_PREFIX + pageNum;

        redis.hexists(cacheKey, pageKey, function (err, data) {
            if (err) return reject(err);
            //缓存存在
            if (data != 0) {
                //查询缓存中的数据
                redis.hget(cacheKey, pageKey, function (err, data) {
                    if (err) return reject(err);
                    return resolve(JSON.parse(data));
                });
            } else {
                return resolve([]);
            }
        });

    });
}

/**
 * 更新徒弟缓存信息
 * @param uid
 * @param pageNum
 * @param users
 * @returns {Promise<unknown>}
 */
exports.updateSonCache = function (uid, pageNum, users) {
    return new Promise((resolve, reject) => {
        let redis = this.app.get("redis");
        let cacheKey = RedisPrefix.SON_LIST_PREFIX + uid;
        let pageKey = RedisPrefix.PAGE_PREFIX + pageNum;

        redis.hset(cacheKey, pageKey, JSON.stringify(users), function (err, data) {
            if (err) return reject(err);
            //设置缓存过期时间
            redis.expire(cacheKey, Constant.USER_TTL, function (err, data) {
            });
            resolve();
        });

    });
}

/**
 * 获取徒孙缓存信息
 * @param uid
 * @param pageNum
 * @returns {Promise<unknown>}
 */
exports.cacheGrandSonList = function (uid, pageNum) {
    return new Promise((resolve, reject) => {
        let redis = this.app.get("redis");
        let cacheKey = RedisPrefix.GRAND_SON_LIST_PREFIX + uid;
        let pageKey = RedisPrefix.PAGE_PREFIX + pageNum;

        redis.hexists(cacheKey, pageKey, function (err, data) {
            if (err) return reject(err);
            //缓存存在
            if (data != 0) {
                //查询缓存中的数据
                redis.hget(cacheKey, pageKey, function (err, data) {
                    if (err) return reject(err);
                    return resolve(JSON.parse(data));
                });
            } else {
                return resolve([]);
            }
        });
    });
}

/**
 * 更新徒孙缓存信息
 * @param uid
 * @param pageNum
 * @param users
 * @returns {Promise<unknown>}
 */
exports.updateGrandSonCache = function (uid, pageNum, users) {
    return new Promise((resolve, reject) => {
        let redis = this.app.get("redis");
        let cacheKey = RedisPrefix.GRAND_SON_LIST_PREFIX + uid;
        let pageKey = RedisPrefix.PAGE_PREFIX + pageNum;

        redis.hset(cacheKey, pageKey, JSON.stringify(users), function (err, data) {
            if (err) return reject(err);
            //设置缓存过期时间
            redis.expire(cacheKey, Constant.USER_TTL, function (err, data) {
            });
            resolve();
        });

    });
}